// Copyright 2024 Vadim Kharitonovich
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lbs

import (
	"context"
	"fmt"
	"net"
	"time"

	"notabug.org/overflowingd/lbs/pkg/client"
	"notabug.org/overflowingd/lbs/pkg/protocol/packet"
)

type udpclient struct {
	options *client.Options
	conn    net.Conn
}

func Open(ctx context.Context, addr string, opts ...client.Opt) (client.Connection, error) {
	var u = udpclient{
		options: &client.Options{
			ReadTimeout: time.Second * 5,
		},
	}

	for i := range opts {
		opts[i](u.options)
	}

	var dialer net.Dialer

	c, err := dialer.DialContext(ctx, "udp", addr)
	if err != nil {
		return nil, err
	}

	u.conn = c
	return &u, nil
}

func (r *udpclient) Close() error {
	return r.conn.Close()
}

func (r *udpclient) Next() (*packet.Response, error) {
	return r.ProcessRequest(
		packet.NewHeader(packet.RequestNext, packet.WithResponseRequirement()),
	)
}

func (r *udpclient) Retain(index uint64) error {
	request := packet.NewRequest(
		packet.NewHeader(packet.RequestRetain),
	)

	request.Payload = packet.NewRetention(index)
	_, err := r.ProcessRequest(request)
	return err
}

func (r *udpclient) ProcessRequest(requestable packet.Requestable) (*packet.Response, error) {
	_, err := r.conn.Write(requestable.Serialize())
	if err != nil {
		return nil, fmt.Errorf("conn write: %w", err)
	}

	if !requestable.RequiresResponse() {
		return nil, nil
	}

	buf := make([]byte, packet.ResponseSizeMax)
	r.conn.SetReadDeadline(time.Now().Add(r.options.ReadTimeout))
	n, err := r.conn.Read(buf)
	if err != nil {
		return nil, fmt.Errorf("conn read: %w", err)
	}

	response, err := packet.ParseResponse(buf[:n])
	if err != nil {
		return nil, fmt.Errorf("packet: parse response: %w", err)
	}

	return response, nil
}
